﻿#region License
/*

	Copyright (C) 2008 Oliver Charles, Daniel Hollander

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
*/
#endregion

using System.Collections.Generic;
using System.Collections.ObjectModel;
using Moebius.Components;

namespace Moebius.Rendering
{
    /// <summary>
    /// The basis for all rendering subsystems.
    /// </summary>
    public abstract class RenderingSubsystem : GenericSubsystem<Image>
    {
        private readonly List<Image> images = new List<Image>();

        /// <summary>
        /// All images that this <see cref="RenderingSubsystem"/> manages.
        /// </summary>
        public ReadOnlyCollection<Image> Images
        {
            get { return images.AsReadOnly(); }
        }

        public override void Register(World world)
        {
            base.Register(world);
            world.EntityRemoved += OnEntityRemoved;
        }

        void OnEntityRemoved(object sender, EntityRemovedEventArgs e)
        {
            Image image = images.Find(delegate(Image img) { return img.Entity == e.Entity; });
            images.Remove(image);
        }

        /// <summary>
        /// Create a new renderable component - <see cref="Image"/>.
        /// </summary>
        /// <param name="entity">The <see cref="Entity"/> that requires the component.</param>
        /// <returns>A new <see cref="Image"/> instance.</returns>
        protected override Image CreateComponent(Entity entity)
        {
            Image image = CreateImage(entity);
            images.Add(image);
            images.Sort(delegate(Image lhs, Image rhs)
                            {
                                if (lhs.Layer > rhs.Layer) return -1;
                                if (lhs.Layer < rhs.Layer) return 1;
                                return 0;
                            });
            return image;
        }

        /// <summary>
        /// Create the <see cref="Image"/> component.
        /// </summary>
        /// <param name="entity">The <see cref="Entity"/> that requires the <see cref="Image"/> component.</param>
        /// <returns>The <see cref="Image"/> component.</returns>
        protected abstract Image CreateImage(Entity entity);
    }
}